<template>
  <div ref="chartDom" :style="{ width: width, height: height }"></div>
</template>
  
  <script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick,useTemplateRef } from "vue";
import { useWindowSize } from "@vant/use";
import * as echarts from "echarts/core";
import { GridComponent, TooltipComponent } from "echarts/components";
import { LineChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";

// 按需引入 ECharts 模块
echarts.use([GridComponent, LineChart, CanvasRenderer, TooltipComponent]);

// 定义 Props
const props = defineProps({
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "400px",
  },
  option: {
    type: Object,
    required: true,
  },
});

// 绑定 DOM 元素
const chartDom = useTemplateRef('chartDom');
let chartInstance = null; // ECharts 实例

// 初始化图表
const initChart = () => {
  if (!chartDom.value) {
    console.error("DOM 元素未找到！");
    return;
  }

  // 确保 DOM 已渲染且尺寸有效
  nextTick(() => {
    chartInstance = echarts.init(chartDom.value);
    chartInstance.setOption(props.option);
  });
};

// 监听窗口尺寸变化
const { width: windowWidth, height: windowHeight } = useWindowSize();
watch([windowWidth, windowHeight], () => {
  if (chartInstance) {
    nextTick(() => {
      chartInstance.resize(); // 窗口变化时重新调整图表
    });
  }
});

// 监听 option 变化
watch(
  () => props.option,
  (newOption) => {
    if (chartInstance) {
      chartInstance.setOption(newOption);
    }
  },
  { deep: true }
);

// 生命周期
onMounted(() => {
  initChart(); // 确保在 DOM 挂载后初始化
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose(); // 销毁实例
  }
});
</script>